//
//  InformationCollectionViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/7.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "InformationCollectionViewController.h"
#import "UIImagePickerController+Edit.h"
#import "FileManagementTableViewCell.h"
#import "OnlyPhotoPopView.h"

static NSString * Identifer = @"identifier";

@interface InformationCollectionViewController ()
<UITextViewDelegate,UITableViewDelegate,UITableViewDataSource> {
    NSString *code;
    NSInteger count;
    NSString *AAC001;
}
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroview;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *BGbutton;
@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *textNumberLabel;
@property (weak, nonatomic) IBOutlet UIButton *submitbutton;
@property (weak, nonatomic) IBOutlet UIButton *addimageButton;
@property (strong, nonatomic) NSMutableArray *regionArray;

@property (nonatomic,strong) NSMutableArray * images;

@end

@implementation InformationCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _images = [NSMutableArray array];
    _regionArray = [NSMutableArray array];
    _BGbutton.alpha = 0;
    count = 1;
    _tableView.frame = flexibleFrame(CGRectMake(0, 107, 320, 0), NO);
    [self initViewLayout];
}
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    self.scroview.contentSize = flexibleSize(CGSizeMake(0, 504), NO);
    
    _submitbutton.layer.cornerRadius = 20*VerticalRatio();
    _textView.delegate = self;
    
}
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if (self.textView.text.length > 0) {
        self.textLabel.hidden = YES;
    }else{
        self.textLabel.hidden = NO;
    }
    if (textView.text.length > 200) {
        NSString *str = [_textView.text substringWithRange:NSMakeRange(0,200)];
        _textView.text = str;
        [_textView resignFirstResponder];
        [[CWHUDTips sharedInstance]  showTips:@"不能超过200字"  withStatus:1 dismissAfter:1.5];
    }
    _textNumberLabel.text = [NSString stringWithFormat:@"%d/200",textView.text.length];
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark - 镇列表
- (void)getpoorAreaTown {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_poorAreaTown withHttpType:@"POST" withTag:F_F_poorAreaTown];
}
#pragma mark - 村列表
- (void)getpoorAreaCountry {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:code forKey:@"code"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_poorAreaCountry withHttpType:@"POST" withTag:F_F_poorAreaCountry];
}

#pragma mark - 选择扶贫对象
- (IBAction)choose:(id)sender {
    [self getpoorAreaTown];
}
- (IBAction)button:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = flexibleFrame(CGRectMake(0, 107, 320, 0), NO);
        _BGbutton.alpha = 0;
    }];
    count = 1;
}

#pragma mark - 上传图片
- (IBAction)addImage:(id)sender {
    [self hideKeyBoard];
    if (_images.count == 3) {
        [[CWHUDTips sharedInstance]  showTips:@"最多添加3张图片"  withStatus:1 dismissAfter:1.5];
        return;
    }
    OnlyPhotoPopView * photoPopView = [[OnlyPhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.addimageButton.frame = flexibleFrame(CGRectMake(5+(_images.count+1)*70, 155, 65, 65), NO);
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:flexibleFrame(CGRectMake(5+_images.count*70, 155, 65, 65), NO)];
                    imageView.image = image;
                    [self.scroview addSubview:imageView];

                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.addimageButton.frame = flexibleFrame(CGRectMake(5+(_images.count+1)*70, 155, 65, 65), NO);
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:flexibleFrame(CGRectMake(5+_images.count*70, 155, 65, 65), NO)];
                    imageView.image = image;
                    [self.scroview addSubview:imageView];

                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.addimageButton.frame = flexibleFrame(CGRectMake(5+(_images.count+1)*70, 155, 65, 65), NO);
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:flexibleFrame(CGRectMake(5+_images.count*70, 155, 65, 65), NO)];
                    imageView.image = image;
                    [self.scroview addSubview:imageView];

                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.addimageButton.frame = flexibleFrame(CGRectMake(5+(_images.count+1)*70, 155, 65, 65), NO);
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:flexibleFrame(CGRectMake(5+_images.count*70, 155, 65, 65), NO)];
                    imageView.image = image;
                    [self.scroview addSubview:imageView];

                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
        }
        
    }];
    [photoPopView show];
}
#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = [NSString stringWithFormat:@"%@",IP_Address_IMAGE];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.7);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [ [Common getLoginInfo] objectForKey:Key_User_password];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    //    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    NSString * image = dictionary[@"data"];
    [_images addObject:image];
    if (image.length>0){
//        _headImageStr = image;
    }else{
//        _headImageStr = @"";
    }
}


#pragma mark - 提交
- (IBAction)submit:(id)sender {
    
    if ([Common dataIsNULL:AAC001]) {
        [[CWHUDTips sharedInstance]  showTips:@"请选择扶贫对象"  withStatus:1 dismissAfter:1.5];
        return;
    }
    if ([Common dataIsNULL:_textView.text]) {
        [[CWHUDTips sharedInstance]  showTips:@"请具体描素扶贫对象"  withStatus:1 dismissAfter:1.5];
        return;
    }
    if (_images.count == 0) {
        [[CWHUDTips sharedInstance]  showTips:@"请添加图片"  withStatus:1 dismissAfter:1.5];
        return;
    }
    
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[Common stringFromData:[Common getLoginInfo][Key_User_userId]] forKey:@"accId"];
    [dic setObject:AAC001 forKey:@"farmId"];
    [dic setObject:code forKey:@"address"];
    [dic setObject:[self.textView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"details"];
    NSString * imagesStr = @"";
    for (int i = 0; i<_images.count; i++) {
        NSString * image = [NSString stringWithFormat:@"%@,",_images[i]];
        if (i==_images.count-1) {
            image = _images[i];
        }
       imagesStr = [imagesStr stringByAppendingString:image];
    }
    [dic setObject:imagesStr forKey:@"image"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_messageCollection withHttpType:@"POST" withTag:F_F_messageCollection];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _regionArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FileManagementTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Identifer];
    if (cell == nil) {
        cell= [[FileManagementTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifer];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    NSDictionary *dic = _regionArray[indexPath.row];
    if (count == 3) {
        cell.titleLabel.text = [Common stringFromData:dic[@"NAME"]];
    } else {
        cell.titleLabel.text = [Common stringFromData:dic[@"address"]];
    }
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self hideKeyBoard];
    if (count == 1) {
        count++;
        code = [Common stringFromData:_regionArray[indexPath.row][@"code"]];
        [self getpoorAreaCountry];
    } else if (count == 2) {
        count++;
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        code = [Common stringFromData:_regionArray[indexPath.row][@"code"]];
        [dic setObject:_regionArray[indexPath.row][@"code"] forKey:@"areaCode"];
        self.shareApi.delegate = self;
        [self.shareApi  requestOperationWithDic:dic withPath:F_getFarmerList withHttpType:@"POST" withTag:F_F_getFarmerList];
    } else if (count == 3) {
        _nameLabel.text = [Common stringFromData:_regionArray[indexPath.row][@"NAME"]];
        AAC001 = [Common stringFromData:_regionArray[indexPath.row][@"AAC001"]];
        count = 1;
        [UIView animateWithDuration:0.5 animations:^{
            _tableView.frame = flexibleFrame(CGRectMake(0, 107, 320, 0), NO);
            _BGbutton.alpha = 0;
        }];
    }
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    if (tag==F_F_poorAreaTown || tag==F_F_poorAreaCountry || tag==F_F_getFarmerList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            if (count == 3) {
                _regionArray = database[@"rows"];
            } else {
                _regionArray = database[@"data"];
            }
            
            
            _tableView.dataSource = self;
            _tableView.delegate = self;
            CGFloat hight = _regionArray.count*45;
            if (hight > 461) {
                hight = 461;
            }
            [UIView animateWithDuration:0.5 animations:^{
                _tableView.frame = flexibleFrame(CGRectMake(0, 107, 320, hight), NO);
                _BGbutton.alpha = 1;
            }];
            [_tableView reloadData];
        }else  {
            
        }
    } else if (tag==F_F_messageCollection) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            [[CWHUDTips sharedInstance]  showTips:@"提交成功"  withStatus:1 dismissAfter:1.5];
            [self backBtn];
        }else  {
            [[CWHUDTips sharedInstance]  showTips:@"提交失败"  withStatus:1 dismissAfter:1.5];
        }
    }
    
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
    
}
@end
